/**
 * 
 */
package com.snail.readyvr.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.widget.Toast;

import com.snail.readyvr.R;
import com.snail.readyvr.util.LogUtils;
import com.snail.readyvr.util.ToastUtils;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * 继承了BaseActivity，实现Android6.0的运行时权限检测
 * 需要进行运行时权限检测的Activity可以继承这个类
 *
 */
public abstract class CheckPermissionsActivity extends BaseActivity
		implements
			ActivityCompat.OnRequestPermissionsResultCallback {
	/**
	 * 需要进行检测的权限数组
	 */
	protected String[] needPermissions = {
			Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE };//这个权限是统计必备的，复写权限的时候，一定要加上此权限
	
	private static final int PERMISSON_REQUESTCODE = 0;
	
	/**
	 * 判断是否需要检测，防止不停的弹框
	 */
	private boolean isNeedCheck = true;

	private boolean hasCallGetAllPermissions = false;//防止代码，重复执行
	protected boolean hasGetAllPermissions = false;//防止activity 在其他生命周期执行需要权限的代码
	protected boolean isCheckDangerousPermission = false;
	protected boolean hasGetDangerousPermission = true;
	//protected boolean hasCallMustOnResume = false;

	private static final int CODE_WRITE_SETTINGS_PERMISSION = 1;

	@Override
	protected void onResume() {
		super.onResume();

		if(isCheckDangerousPermission)
			checkSettingPermission();

		if(isNeedCheck){
			checkPermissions(needPermissions);
		}
	}
	
	/**
	 * 
	 * @param permissions
	 *
	 *
	 */
	private void checkPermissions(String... permissions) {
		List<String> needRequestPermissonList = findDeniedPermissions(permissions);
		if (null != needRequestPermissonList
				&& needRequestPermissonList.size() > 0) {
			hasGetAllPermissions = false;
			ActivityCompat.requestPermissions(this,
					needRequestPermissonList.toArray(
							new String[needRequestPermissonList.size()]),
					PERMISSON_REQUESTCODE);
		}else if(null != needRequestPermissonList && needRequestPermissonList.size() == 0){
			hasGetAllPermissions = true;
			if(hasGetDangerousPermission)
			  mustCallOnResume();
			initUMeng();
			if(!hasCallGetAllPermissions && hasGetDangerousPermission) {
				hasGetAllPermissions();
				hasCallGetAllPermissions = true;
			}
		}
	}

	private void initUMeng() {
		MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType. E_UM_NORMAL);
		MobclickAgent.onResume(this);
	}

	/**
	 * 获取权限集中需要申请权限的列表
	 * 
	 * @param permissions
	 * @return
	 *
	 *
	 */
	private List<String> findDeniedPermissions(String[] permissions) {
		List<String> needRequestPermissonList = new ArrayList<String>();
		for (String perm : permissions) {
			if (ContextCompat.checkSelfPermission(this,
					perm) != PackageManager.PERMISSION_GRANTED
					|| ActivityCompat.shouldShowRequestPermissionRationale(
							this, perm)) {
				needRequestPermissonList.add(perm);
			} 
		}
		return needRequestPermissonList;
	}

	/**
	 * 检测是否说有的权限都已经授权
	 * @param grantResults
	 * @return
	 *
	 */
	private boolean verifyPermissions(int[] grantResults) {
		for (int result : grantResults) {
			if (result != PackageManager.PERMISSION_GRANTED) {
				return false;
			}
		}
		return true;
	}

	@Override
	public void onRequestPermissionsResult(int requestCode,
										   String[] permissions, int[] paramArrayOfInt) {
		if (requestCode == PERMISSON_REQUESTCODE) {
			if (!verifyPermissions(paramArrayOfInt)) {
				showMissingPermissionDialog();
				isNeedCheck = false;
				hasGetAllPermissions = false;
			}else {
				hasGetAllPermissions = true;
				if(hasGetDangerousPermission)
					mustCallOnResume();
				initUMeng();
				if (!hasCallGetAllPermissions && hasGetDangerousPermission) {
					hasGetAllPermissions();
					hasCallGetAllPermissions = true;
				}
			}
		}
	}

	/**
	 * 显示提示信息
	 *
	 *
	 */
	private void showMissingPermissionDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.notifyTitle);
		builder.setMessage(R.string.notifyMsg);

		// 拒绝, 退出应用
		builder.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});

		builder.setPositiveButton(R.string.setting,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						startAppSettings();
						isNeedCheck = true;
					}
				});

		builder.setCancelable(false);

		builder.show();
	}

	/**
	 *  启动应用的设置
	 *
	 */
	private void startAppSettings() {
		Intent intent = new Intent(
				Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		intent.setData(Uri.parse("package:" + getPackageName()));
		startActivity(intent);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	protected abstract void hasGetAllPermissions();


	@Override
	protected void onPause() {
		super.onPause();

		//hasCallMustOnresume = false;

		if(hasGetAllPermissions){
			MobclickAgent.onPause(this);
		}
	}

	/**
	 * 在onresum里面必须要调用，而且必须要权限的，调用此方法
	 */

	protected  void mustCallOnResume(){};

	private void checkSettingPermission() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			hasGetDangerousPermission = Settings.System.canWrite(this);
		} else {
			hasGetDangerousPermission = true;
		}
		if (hasGetDangerousPermission) {
			if(!hasCallGetAllPermissions && hasGetAllPermissions) {
				hasGetAllPermissions();
				hasCallGetAllPermissions = true;
			}
		} else {
			if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
				ToastUtils.show(this,R.string.high_settings);
				if(Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.M)
					ToastUtils.show(this,R.string.high_settings_tip, Toast.LENGTH_LONG);
				Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
				intent.setData(Uri.parse("package:" + this.getPackageName()));
				this.startActivityForResult(intent, CODE_WRITE_SETTINGS_PERMISSION);
			}
		}
	}

	@SuppressLint("NewApi")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CODE_WRITE_SETTINGS_PERMISSION && Settings.System.canWrite(this)){
			hasGetDangerousPermission = true;
			if(hasGetAllPermissions)
				mustCallOnResume();
			if(!hasCallGetAllPermissions && hasGetAllPermissions) {
				hasGetAllPermissions();
				hasCallGetAllPermissions = true;
			}
			LogUtils.d("onActivityResult CODE_WRITE_SETTINGS_PERMISSION");
		}else {
			hasGetDangerousPermission = false;
			ToastUtils.show(this,R.string.high_settings_faile);
		}
	}
}
